﻿using System;

namespace HelpersDotNet.Extensions
{
    public static partial class Extensions
    {
        /// <summary>
        /// Check if a number is a power of 2.
        /// </summary>
        /// <param name="number">The number to check.</param>
        /// <returns>Returns true if the number is power of 2.</returns>
        /// <remarks>
        /// Note that powers of two have only 1 bit set to one:
        /// 1:  000001
        /// 2:  000010
        /// 4:  000100
        /// 8:  001000
        /// 16: 010000
        /// 32: 100000
        /// and so on, so we need to check if the number only has one bit that is set,
        /// and that the number is not 0 (because zero is not a power of two).
        /// 
        /// We can count the number of set bits (which is another interview question!), 
        /// and if the number of set bits is one, then the number is a power of two. 
        /// A smarter way to do it would be bitwise ANDing of the number and the number-1,
        /// and then check that the result == 0.
        /// For example, to check that 32 is a power of 2, convert 32 to binary to be 100000, 
        /// convert 31 to binary to be 011111. Bitwise ANDing of those 2 numbers would obviously result in 0.
        /// </remarks>
        public static bool IsPowerOfTwo(this int number)
        {
            return ((number != 0) && (number & (number - 1)) == 0);
        }

        public static string ToBinary(this int number, int numberOfBits)
        {
            if (numberOfBits <= 0)
                throw new ArgumentOutOfRangeException("numberOfBits", "Must be positive integer");

            string ret, str;
            ret = "";
            str = Convert.ToString(number, 2);
            if (str.Length > numberOfBits)
                throw new Exception("Error converting");
            for (int i = str.Length; i < numberOfBits; ++i)
                ret += "0";
            ret += str;
            return ret;
        }

    }
}
